package com.gitee.feizns.quickstart.mybatis.flex;

import com.gitee.feizns.quickstart.mybatis.flex.domain.Column;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.table.TableInfoFactory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 常用函数
 * @author feizns
 * @since 2025/3/27
 */
public interface Mysql {

    /**
     * 截断指定类型的表
     * @param type 类型
     * @return int
     */
    static int truncate(Class<?> type) {
        return Db.updateBySql("TRUNCATE " + TableInfoFactory.ofEntityClass(type).getTableName());
    }

    /**
     * 查询
     * @return {@link List}<{@link Map}<{@link String}, {@link Object}>>
     */
    static List<Map<String, Object>> select(String sql) {
        return Db.selectListBySql(sql).stream().map(Row::toCamelKeysMap).collect(Collectors.toList());
    }

    /**
     * 数据库名称
     * @return {@link String }
     */
    static String database() {
        return Db.selectOneBySql("SELECT DATABASE()").toObject(String.class);
    }

    /**
     * 所有表
     * @return {@link List }<{@link String }>
     */
    static List<String> tables() {
        return Db.selectListBySql("SHOW TABLES").stream()
                .map(row -> row.toObject(String.class))
                .collect(Collectors.toList());
    }

    /**
     * 列
     * @param type 类型
     * @return {@link List }<{@link Column }>
     */
    static List<Column> columns(Class<?> type) {
        List<Row> rows = Db.selectListBySql("SELECT ORDINAL_POSITION as ordinal, COLUMN_NAME as `name`, IS_NULLABLE as `nullable`, DATA_TYPE as dataType, COLUMN_TYPE as columnType, COLUMN_KEY as `key`, column_comment as `comment` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_NAME = " + TableInfoFactory.ofEntityClass(type).getTableName());
        return rows.stream().map(row -> row.toObject(Column.class)).collect(Collectors.toList());
    }

}
